import { OnInit, Component, ViewChild, TemplateRef } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { SettingsService } from '@delon/theme'
import { ACLService } from '@delon/acl'
import { STColumn, STData } from '@delon/abc'

import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { I18NService } from '@core'
import { ISearchSchema, ISearchOption } from '@shared/interfaces/search'
import { ESearchType } from '@shared/enums'
import { EDateLimitEnum, Currency } from '@shared/interfaces/common'
import { today, TradeAmountMaxValue } from 'app/utils/contraints'
import { DepositService } from '../deposit.service'
import { EDepositType, EDepositStatus, IDeposit } from '@shared/interfaces/deposit'
import { User } from '@shared/interfaces/user'
import { AAMSFilterInit } from '@shared/interfaces/aams'

@Component({
  selector: 'app-merchant-deposit-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../../shared/styles/table.less'],
})
export class DepositListComponent extends ListBaseClass<any, any> implements OnInit, AAMSFilterInit {
  @ViewChild('transAmt') transAmt: TemplateRef<void>
  @ViewChild('insTpl') insTpl: TemplateRef<void>
  @ViewChild('agentTpl') agentTpl: TemplateRef<void>
  @ViewChild('merchantTpl') merchantTpl: TemplateRef<void>
  @ViewChild('storeTpl') storeTpl: TemplateRef<void>
  @ViewChild('tplCurrency') tplCurrency: TemplateRef<void>

  TradeAmountMaxValue = TradeAmountMaxValue

  math = Math // 引用使 html 可以调用
  transAmtFrom = '' // 交易金额从
  transAmtTo = '' // 交易金额到
  internalDepositType = EDepositType
  internalDepositStatus = EDepositStatus

  selectedCurrency: Currency
  searchSchema: ISearchSchema[] = []
  columns: STColumn[] = []
  procFlagOptions: ISearchOption[] = []

  /** 当前用户 */
  user: User

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    public settings: SettingsService,
    public aclService: ACLService,
    public depositService: DepositService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit() {
    this.user = { ...this.settings.user } as User
    this.initSearchParams()
    this.parseParams().subscribe(() => {
      this.queryTableDataWithParams()
      this.initColumns()
    })
    this.initialAAMSFilter()
  }

  initialAAMSFilter() {
    this.initAcquirer()
  }

  initSearchParams(): void {
    this.searchSchema = [
      {
        label: 'Operated At',
        labelI18n: 'GENERAL.INFO.OPERATED_AT',
        index: ['createdAtFrom', 'createdAtTo'],
        type: ESearchType.dateRange,
        allowClear: false,
        dateLimitType: EDateLimitEnum.Month,
        value: [today, today],
      },
      {
        label: '目标金额',
        labelI18n: 'OPERATION.DEPOSIT.TARGET_AMT',
        index: ['transAmtFrom', 'transAmtTo'],
        component: this.transAmt,
        customFunc: () => [this.transAmtFrom, this.transAmtTo],
      },
      {
        label: '清算币种',
        labelI18n: 'GENERAL.INFO.SETTLEMENT_CURRENCY',
        index: 'currency',
        component: this.tplCurrency,
        customFunc: () => (this.selectedCurrency ? this.selectedCurrency.code : ''),
      },
      {
        label: '操作类型',
        labelI18n: 'OPERATION.DEPOSIT.LIST.OPERATION_TYPE',
        index: 'depositType',
        type: ESearchType.selection,
        options: [
          {
            label: this.trans('DEPOSIT.OPERATION_TYPE.COLLECTION'),
            value: `${EDepositType.Collection}`,
          },
          {
            label: this.trans('DEPOSIT.OPERATION_TYPE.RETURN'),
            value: `${EDepositType.Return}`,
          },
        ],
      },
      {
        label: '状态',
        labelI18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        type: ESearchType.selection,
        options: [
          {
            label: this.trans('DEPOSIT.STATUS.PROCESSING'),
            value: `${EDepositStatus.Processing}`,
          },
          {
            label: this.trans('DEPOSIT.STATUS.FINISH'),
            value: `${EDepositStatus.Finish}`,
          },
          {
            label: this.trans('DEPOSIT.STATUS.ABORT'),
            value: `${EDepositStatus.Abort}`,
          },
        ],
      },
      {
        label: '机构',
        labelI18n: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        index: 'insCode',
        component: this.insTpl,
        customFunc: () => (this.selectedAcquirer ? this.selectedAcquirer.code : ''),
      },
      {
        label: '集团',
        labelI18n: 'GENERAL.BIZ_LEVEL.AGENT',
        index: 'agentCode',
        component: this.agentTpl,
        customFunc: () => (this.selectedGroup ? this.selectedGroup.code : ''),
      },
      {
        label: '商户',
        labelI18n: 'GENERAL.BIZ_LEVEL.MERCHANT',
        index: 'intMerCode',
        component: this.merchantTpl,
        customFunc: () => (this.selectedMerchant ? this.selectedMerchant.code : ''),
      },
      {
        label: '门店',
        labelI18n: 'GENERAL.BIZ_LEVEL.STORE',
        index: 'intStoreCode',
        component: this.storeTpl,
        customFunc: () => (this.selectedStore ? this.selectedStore.code : ''),
      },
    ]
  }

  initColumns(): void {
    this.columns = [
      {
        type: 'link',
        title: '操作编号',
        i18n: 'OPERATION.DEPOSIT.OPERATION_ID',
        index: 'operationID',
        className: 'text-center',
        width: '150px',
        fixed: 'left',
        click: (record: STData) => this.goDetail(record as IDeposit),
      },
      {
        title: '门店名称',
        index: 'storeName',
        i18n: 'GENERAL.STORE.NAME',
        width: '150px',
        className: 'text-center',
      },
      {
        title: '操作时间',
        i18n: 'GENERAL.INFO.OPERATED_AT',
        index: 'createdAt',
        className: 'text-center',
        type: 'date',
        width: '150px',
        dateFormat: 'YYYY-MM-DD HH:mm',
      },
      {
        title: '操作类型',
        i18n: 'OPERATION.DEPOSIT.LIST.OPERATION_TYPE',
        className: 'text-center',
        width: '100px',
        render: 'depositType',
      },
      {
        title: '目标金额',
        i18n: 'OPERATION.DEPOSIT.TARGET_AMT',
        type: 'currency',
        width: '100px',
        render: 'depositAmt',
      },
      {
        title: '状态',
        i18n: 'GENERAL.INFO.STATUS',
        className: 'text-center',
        width: '100px',
        fixed: 'right',
        render: 'status',
      },
    ]
  }

  /** 交易金额校验 */
  validateTransAmt() {
    const transAmtFromVal = this.transAmtFrom as any
    const transAmtToVal = this.transAmtTo as any

    if (
      (!isNaN(transAmtFromVal) &&
        (transAmtFromVal > Number.MAX_SAFE_INTEGER || transAmtFromVal > TradeAmountMaxValue)) ||
      (!isNaN(transAmtToVal) && (transAmtToVal > Number.MAX_SAFE_INTEGER || transAmtToVal > TradeAmountMaxValue))
    ) {
      this.msg.error(this.trans('VALIDATION.MAX_VALUE', { value: TradeAmountMaxValue }))
      this.searchValid = false
      return
    }

    if (!isNaN(transAmtFromVal) && !isNaN(transAmtToVal) && transAmtFromVal > transAmtToVal) {
      this.msg.error(this.trans('TRADE.MIN_AMT_LTE_MAX_AMT'))
      this.searchValid = false
      return
    }

    this.searchValid = true
  }

  checkSearchParamsValidation(): boolean {
    const transAmtFromVal = parseInt(this.transAmtFrom, 10)
    const transAmtToVal = parseInt(this.transAmtTo, 10)

    if (!isNaN(transAmtFromVal) || !isNaN(transAmtToVal)) {
      if (!this.selectedCurrency) {
        this.msg.error(
          this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('GENERAL.INFO.TRANSACTION_CURRENCY') }),
        )
        return false
      }
    }
    return this.searchValid
  }

  goCollectDeposit() {
    this.router.navigate(['../new/collection'], { relativeTo: this.route })
  }

  goReturnDeposit() {
    this.router.navigate(['../new/return'], { relativeTo: this.route })
  }

  queryTableDataWithParams(): void {
    this.loading = true
    this.depositService.getList(this.params).subscribe(this.renderList.bind(this), this.getListError.bind(this))
  }

  goDetail(record: IDeposit): void {
    this.router.navigate([`../${record.operationID}`], { relativeTo: this.route })
  }
}
